/**
 * Copyright ? 2015-2035 万雍科技 All Rights Reserved.  
 * File name:      OrgManageService.java
 * Date:           2015-12-21
 * Description:    机构管理
 * Modify History:     Date             Programmer       Notes
 *                    ---------        ---------------  ---------
 *                    2015-12-25        张旭星                           Initial
 **********************************************************************/
package com.wy.framework.services.org;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wy.framework.constants.Constants;
import com.wy.framework.constants.DBConstant;
import com.wy.framework.constants.FieldConstant;
import com.wy.framework.constants.RtnCodeConstant;
import com.wy.framework.dao.ErrorSqlException;
import com.wy.framework.exceptions.ServiceException;
import com.wy.framework.pojos.TSysOrginfo;
import com.wy.framework.pojos.TSysUserinfo;
import com.wy.framework.services.AbstractBaseService;
import com.wy.framework.services.login.LoginService;
import com.wy.business.developer.developer.services.RegistService;
import com.wy.component.dataConvert.BeanUtil;
import com.wy.component.image.ImageUtil;
import com.wy.component.properties.PropertiesUtil;

public class OrgManageService extends AbstractBaseService {

	private static Logger logger = LoggerFactory
			.getLogger(OrgManageService.class);
	
	@Autowired
	protected LoginService loginService;
	
	@Autowired
	private RegistService registService;

	/**
	 * 查询全部机构信息
	 */
	public List<Map> queryOrgInfo(TSysUserinfo loginUser)
			throws ServiceException {
		try {
			List<Map> orgInfoMapList = new ArrayList<Map>();
			// 查询机构信息
			List param = new ArrayList();
			param.add(loginUser.getDept());
			List<Map> orgInfoList = dataBaseDao.queryForList(
					"TC_Sys_OrgInfo.queryOrgInfo", param);
			for (Map orgInfo : orgInfoList) {
				// // 查询机构种类、是否金交所会员
				// Map orgType = getOrgType((String) orgInfo.get("orgCode"));
				// orgInfo.putAll(orgType);
				// 翻译相关字段
				msgSourceAdapter.translateMap(orgInfo,
						FieldConstant.isAvailable);
				Map temp = new HashMap();
				temp.put("orgInfo", orgInfo);
				orgInfoMapList.add(temp);
			}
			return orgInfoMapList;
		} catch (Exception e) {
			logger.error("系统错误:{}", e);
			// e.printStackTrace();
			throw new ServiceException(e);
		}
	}

	/**
	 * 新增机构信息
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Map saveOrgInfo(TSysOrginfo orgInfo) throws ServiceException {
		try {
//			if(StringUtils.isNotEmpty(orgInfo.getFileDiskName()))
//				orgInfo.setLogo(orgInfo.getFileDiskName());
			orgInfo.setOrgCode(UUID.randomUUID().toString());
			orgInfo.flushUpdateTime();
			dataBaseDao.save(orgInfo);
			//如果是二级节点,自动新增其它这个部门
			if(StringUtils.equals(orgInfo.getParentOrgCode(), "000000") && !StringUtils.equals(new PropertiesUtil().getAppProperties("projectName"),Constants.PROJECT_NAME_QNJ)){
				TSysOrginfo tcSysOrgInfo = new TSysOrginfo();
				tcSysOrgInfo.setOrgCode(UUID.randomUUID().toString());
				tcSysOrgInfo.setOrgName("外部人员");
				tcSysOrgInfo.setIsAvailable("1");
//				tcSysOrgInfo.setCancellationDate(new Date());
				tcSysOrgInfo.setUpdateTime(new Date());
//				tcSysOrgInfo.setOtherFlag("1");
				tcSysOrgInfo.setParentOrgCode(orgInfo.getOrgCode());
				this.dataBaseDao.save(tcSysOrgInfo);
			}
			Map result = new HashMap();
			result.put("RspCode", RtnCodeConstant.RTN_CODE_SUCCESS);
			result.put("OrgInfo", orgInfo);
			return result;
		} catch (Exception e) {
			logger.error("系统错误:{}", e);
			throw new ServiceException(e);
		}
	}

	/**
	 * 更新机构信息
	 * @throws ErrorSqlException 
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String  updateOrgInfo(String orgCode,String orgName,String state) throws ServiceException, ErrorSqlException {
		TSysOrginfo tSysOrginfo=(TSysOrginfo) dataBaseDao.getHibernateTemplate().load(TSysOrginfo.class, orgCode);
		tSysOrginfo.setOrgName(orgName);
		tSysOrginfo.flushUpdateTime();
		tSysOrginfo.setIsAvailable(state);
		dataBaseDao.update(tSysOrginfo);
		return RtnCodeConstant.RTN_CODE_SUCCESS;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List<Map> queryParentOrg(String orgCode)throws ServiceException{
		List<Map> list=null;
		try {
		  list=dataBaseDao.queryForList("t_sys_orginfo.loadParentOrgName", orgCode);
		} catch (ErrorSqlException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 删除机构信息
	 * @throws ErrorSqlException 
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String deleteOrgInfo(String orgCode) throws ErrorSqlException {
		TSysOrginfo orgInfo = (TSysOrginfo) dataBaseDao.load(TSysOrginfo.class, orgCode);
		List list = dataBaseDao.getHibernateTemplate().find("from TSysUserinfo where dept = ?", orgCode);
		if(list!=null && list.size()>0)
			return RtnCodeConstant.RTN_CODE_D03_ORG_USER_EXIST;
		if (!hasChildrean(orgInfo)) {
			orgInfo.setIsAvailable(Constants.IS_NOT_AVAILABLE);
			dataBaseDao.update(orgInfo);
			logger.info("逻辑删除机构信息");
			return RtnCodeConstant.RTN_CODE_SUCCESS;
		} else {
			return RtnCodeConstant.RTN_CODE_D03_DOWN_ORG_EXIST;
		}
	}
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public boolean hasChildrean(TSysOrginfo orgInfo) {
		List param = new ArrayList();
		param.add(orgInfo.getOrgCode());
		try {
			List list = dataBaseDao.queryForList("t_sys_orginfo.loadchildorg", param);
			return list.size() > 0 ? true : false;
		} catch (ErrorSqlException e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 加载有效机构信息(供下拉选择)
	 */
	public List<Map> loadOrgInfo(TSysUserinfo loginUser)
			throws ServiceException {
		List<Map> orgInfoList = new ArrayList<Map>();
		try {
			List param = new ArrayList();
			param.add(loginUser.getDept());
			param.add(loginUser.getDept());
			orgInfoList = dataBaseDao.queryForList(
					"TC_Sys_OrgInfo.loadOrgInfo", param);
			return orgInfoList;
		} catch (Exception e) {
			logger.error("系统错误:{}", e);
			// e.printStackTrace();
			throw new ServiceException(e);
		}
	}

	/**
	 * 加载有效机构信息(供下拉选择)
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List<Map> loadOrgTreeInfo(String id, TSysUserinfo loginUser)
			throws ServiceException {
		try {
			List<Map> result;
			ArrayList param = new ArrayList();
			if (id == null) {
				param.add(loginUser.getDept());
				result = dataBaseDao.queryForList("t_sys_orginfo.loadrootorg",param);
			} else {
				param.add(id);
				result = dataBaseDao.queryForList("t_sys_orginfo.loadchildorg", param);
			}
			return result;
		} catch (Exception e) {
			logger.error("系统错误:{}", e);
			e.printStackTrace();
			throw new ServiceException(e);
		}
	}

	/**
	 * 按名称加载有效机构信息(供选择)
	 */
	public List<Map> loadOrgInfoByGroup(String regionCode)
			throws ServiceException {
		try {
			List<Map> result = null;
			if (null != regionCode && !regionCode.isEmpty()
					&& regionCode.equals(DBConstant.REGION_ALL)) {
				// 经营地区为全国
				result = this.getDataBaseDao().queryForList(
						"TC_Sys_OrgInfo.loadOrgInfoByGroupAll");
			} else {
				// 人民银行支行根据经营区域
				result = this.getDataBaseDao().queryForList(
						"TC_Sys_OrgInfo.loadOrgInfoByGroup", regionCode);
			}
			return result;
		} catch (Exception e) {
			logger.error("系统错误:{}", e);
			// e.printStackTrace();
			throw new ServiceException(e);
		}
	}

	/**
	 * 加载下拉部门的显示
	 * @return
	 * @throws ErrorSqlException
	 * @throws IOException
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List<Map> loadOrgAllInfo() throws ErrorSqlException, IOException {
		List<Map> result=null;
		result= dataBaseDao.queryForList("t_sys_orgcode.loadOrgAllInfo");
		return BeanUtil.listToTree(result, "ID", "PID");
	}
	
	public List<Map> loadAllOrgForAPP() throws ErrorSqlException, IOException {
		String forSearchUser = ServletActionContext.getRequest().getParameter("forSearchUser");
		List<Map> result=null;
		result= dataBaseDao.queryForList("TC_SYS_Function.loadOrgAllInfoIsNotNull");
		return BeanUtil.listToTree(result, "id", "pid");
	}


	public void checkDept(String orgcode) throws ServiceException {
		try {
			dataBaseDao.update("tc_sys_orginfo.del",orgcode);
		} catch (Exception e) {
			logger.error("系统错误:{}", e);
			throw new ServiceException(e);
		}
	}

	public List<Map> loadMeetUserInfo(String id, TSysUserinfo loginUser)throws ServiceException {
		try {
			String currentRoot = ServletActionContext.getRequest().getParameter("currentRoot");
			List<Map> result;
			ArrayList param = new ArrayList();
			param.add(currentRoot);
			result = dataBaseDao.queryForList("TC_Sys_OrgInfo.loadRootOrgUser",param);
			return result;
		} catch (Exception e) {
			logger.error("系统错误:{}", e);
			e.printStackTrace();
			throw new ServiceException(e);
		}
	}

	public void addOrg(String head,String orgName,String parentOrgCode) throws ErrorSqlException {
		
		TSysOrginfo parentOrginfo=(TSysOrginfo)dataBaseDao.load(TSysOrginfo.class, parentOrgCode);
		TSysOrginfo tSysOrginfo = new TSysOrginfo();
		if(!StringUtils.equals(head, "")){
			head=head.substring(head.lastIndexOf("/upload"));
			tSysOrginfo.setOrgLogo(head);
		}else{
			try {
				tSysOrginfo.setOrgLogo(registService.genDefaultHeadImg(UUID.randomUUID().toString()));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		tSysOrginfo.setOrgName(orgName);
		tSysOrginfo.setParentOrgCode(parentOrgCode);
		
		tSysOrginfo.setOrgCode(UUID.randomUUID().toString());
		tSysOrginfo.setIsAvailable(Constants.IS_AVAILABLE);
		tSysOrginfo.setOperatorAccount(loginUser().getUserId());
		tSysOrginfo.setOperatorName(loginUser().getUserName());
		tSysOrginfo.flushUpdateTime();
		tSysOrginfo.setCreateTime(new Date());
		tSysOrginfo.setOrgType(parentOrginfo.getOrgType());
		dataBaseDao.save(tSysOrginfo);
	}
	
}
